package com.it.controller;

import com.it.pojo.dto.LoginDTO;
import com.it.pojo.entity.Result;
import com.it.pojo.entity.User;
import com.it.pojo.vo.LoginVO;
import com.it.pojo.dto.RegisterDTO;
import com.it.properties.JwtProperties;
import com.it.service.UserService;
import com.it.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserService userService;


    /**
     * 用户登录
     *
     * @param loginDTO 登录参数
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户: {}登录", loginDTO.getUsername());

        User user = userService.login(loginDTO);
        // 登录成功
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        // 生成JWT
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims
        );

        LoginVO loginVO = LoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .build();

        return Result.success(loginVO);
    }

    /**
     * 用户注册
     *
     * @param registerDTO 注册参数
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO) {
        log.info("用户注册: {}", registerDTO);
        userService.add(registerDTO);
        return Result.success();
    }

    /**
     * 用户退出
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        log.info("用户退出");
        return Result.success("成功退出");
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/info")
    public Result<User> info() {
        log.info("获取用户信息");
        return Result.success(userService.getUserInfo());
    }
}
